<template>
  <div>
    <el-form :label-position="'left'" label-width="80px">
      <el-form-item label="发布范围">
        <el-select multiple
                   collapse-tags
                   v-model="member.group_ids"
                   clearable
                   @change="hhhhh"
                   placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面(选填)">
        <el-upload
          class="avatar-uploader"
          action="https://hks-sys.dindong.cn/api/file/upload-img"
          name="photo"
          :show-file-list="false"
          :on-success="handlePhoto"
          :before-upload="beforeAvatarUpload">
          <img v-if="photoImg" :src="photoImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题(必填)">
        <el-input v-model="member.title"></el-input>
      </el-form-item>

      <!-- <el-form-item label="描述">
          <el-input v-model="member.desc" ></el-input>
      </el-form-item>  -->

      <el-form-item label="详情(选填)">
        <vue-ueditor-wrap v-model="member.content" :config="myConfig" @ready="ready"></vue-ueditor-wrap>
      </el-form-item>

      <div class="add-table-wrapper">
        <el-button type="primary" @click="commit" class="add-table-wrapper-btn">发布</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        id: '',
        photoImg: '',
        photoID: '',
        member: {
          title: '',
          desc: '',
          content: '',
          group_ids: []
        },
        group: [],
        groupList:[],
        pageTotal: 0,
        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 500,
          // 初始容器宽度
          initialFrameWidth: '100%',
          // serverUrl: 'http://35.201.165.105:8000/controller.php',
          serverUrl: 'https://bibiji.rzkeji.com/ueditor-php/controller.php',
          // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
          //UEDITOR_HOME_URL: '/peoples_association_backstage/dist//static/UEditor/'
          toolbars: [
            [
              'undo', 'redo', '|',
              'bold', 'italic', 'underline', 'strikethrough',
              'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
              'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
              'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
              'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
              'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
              'simpleupload', 'insertimage', 'insertvideo', 'music',
              'horizontal', 'date', 'time',
              'inserttable'
            ]
          ]
        }

      }
    },
    methods: {
      //获取组列表
      async getGroupList(page){
        let params = {
          page: page || 1,
          limit: this.limit
        }
        const res = await this.$api.getGroupList(params);
        if (res.data.level=='success') {
          if (!page){
            this.groupList = res.data.data;
          } else {
            this.groupList.concat(res.data.data);
          }
          this.pageTotal = res.data.page_info.total
          if (this.groupList.length<this.pageTotal){
            this.getGroupList(params.page+1);
          }
        }else {
          this.$message({
            message: res.data.message,
            type: 'warning'
          });
        }
      },
      beforeAvatarUpload(file) {
        //上传照片前的操作
        // console.log(file,555)
      },
      handlePhoto(res, file) {
        //上传照片成功
        if (res.data) {
          this.photoImg = res.data.img_url;
          this.photoId = res.data.id;
        }
      },
      ready(editorInstance) {
        // 保存原始的 getActionUrl 方法
        // if(!UE.Editor.prototype._bkGetActionUrl){
        //     UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
        // }
        // // 自定义
        // UE.Editor.prototype.getActionUrl = function (action) {
        //     console.log(action)
        //     if (action == 'uploadimage') {
        //     return `https://shop.rzkeji.com/api/other/ueditorAction?action=uploadimage`; // 调整上传图片的接口
        //     } else if (action == 'uploadVideo') {
        //     return `https://shop.rzkeji.com/api/other/ueditorAction?action=uploadVideo`; // 调整上传视频接口
        //     } else {
        //     return this._bkGetActionUrl.call(this, action); // 其他上传使用原始的 getActionUrl 方法
        //     }
        // }
      },
      async getSysNewsDetail() {
        //获取详情
        let params = {id: this.id}
        let res = await this.$api.getSysNewsDetail(params)
        if (res.data.level == 'success' && res.data.data) {
          let data = res.data.data
          this.member.title = data.title;
          this.member.desc = data.content;
          this.member.content = data.detail || '';
          this.photoId = data.img_id;
          this.photoImg = data.img_url;
        }
      },
      async commit() {
        if (this.member.group_ids.length>0&&this.member.group_ids[0]==""){
          this.member.group_ids = [];
        }
        let params = {
          id: this.id,
          title: this.member.title,
          detail: this.member.content,
          img_id: this.photoId,
          content: this.member.desc,
          group_ids: this.member.group_ids
        };
        let res = await this.$api.setSysNews(params);
        if (res.data.level == 'success') {
          this.$message({
            type: 'success',
            message: res.data.message
          })
          setTimeout(() => {
            this.$router.push('System_msg_list')
          }, 2000)
        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }

      },
      querySearch(queryString, cb) {
        var restaurants = this.groupList;
        // var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(restaurants);
      },
      handleSelect(item) {
        console.log(item)
        // this.addForm.level = item.level;
        // this.addForm.link_url = item.link_url
      },
      hhhhh(item){
        if (item.length<this.group.length) {
          if (this.member.group_ids.indexOf("")>-1){
            this.member.group_ids.splice(0,1);
          }
        }else {
          if (item.indexOf("")>-1){
            this.member.group_ids = [""];
            this.groupList.forEach(item=>{
              this.member.group_ids.push(item.id)
            })
          }
        }
        this.group = this.member.group_ids;

      },
    },
    mounted() {
      this.id = this.$route.query.id;
      this.getGroupList();
      if (this.id) {
        this.getSysNewsDetail();
      }
    },
  }
</script>
<style lang="scss" scoped>
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: contain;
  }

  .add-table-wrapper {
    display: flex;
    justify-content: center;
    padding: 30px 0;
  }
</style>
